//
//  PersonCtr.m
//  PearRich
//
//  Created by 谢黎鹏 on 2020/1/11.
//  Copyright © 2020年 谢黎鹏. All rights reserved.
//

#import "PersonCtr.h"
#import "PersonCell.h"
#import "GoodsNameMgrVC.h"
#import "SGQRCodeObtain.h"
#import <PINCache/PINCache.h>
#import "MXActionSheet.h"
#import "ReuseFile.h"
#import "XLPhotoBrowser.h"
#import "QRCodeInputTV.h"
#import "ImageSettingVC.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import "LZiCloud.h"
#import "ExpressCheckView.h"
#import "MoneyChangeVC.h"
#import "TCRedBookDealVC.h"
@interface PersonCtr()<UITableViewDelegate,UITableViewDataSource,XLPhotoBrowserDelegate,TZImagePickerControllerDelegate>
@property(nonatomic,retain)UITableView * myTab;
@property(nonatomic,retain)NSArray * nameArr,*imgArr;
@property(nonatomic,retain)UIView * shelterView;
@end
@implementation PersonCtr
- (void)viewDidLoad{
    [super viewDidLoad];
    self.myTitle = @"我的";

    self.nameArr = @[@[@"设置logo",iPhoneX?@"扫脸识别":@"指纹识别",@"手势密码"],@[@"文字识别",@"生成二维码",@"快递查询",@"汇率换算",@"小红书"]];
    self.imgArr = @[@[@"商品",@"图片",@"指纹",@"手势密码"],@[@"文字",@"二维码",@"快递",@"汇率换算",@"汇率换算"]];
    [self.view addSubview:self.myTab];
}
-(UITableView*)myTab{
    if (_myTab == nil) {
        _myTab = [[UITableView alloc]initWithFrame:Frame(0, kTopHeight, IPHONE_WIDTH, IPHONE_HEIGHT-kTabbarHeight-kTopHeight) style:UITableViewStyleGrouped];
        _myTab.delegate = self;
        _myTab.dataSource = self;
        _myTab.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _myTab;
}
#pragma mark tableView代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.nameArr.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray * arr = self.nameArr[section];
    return arr.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PersonCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(!cell){
        cell = [[PersonCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    NSArray * arr = self.nameArr[indexPath.section];
    cell.imgName = self.imgArr[indexPath.section][indexPath.row];
    cell.name = arr[indexPath.row];
    if (indexPath.row == 0) {
        cell.firstRow = YES;
    }else if (indexPath.row == arr.count - 1){
        cell.lastRow = YES;
    }
    if (indexPath.section==0 && indexPath.row >0){
        cell.isShowSw = YES;
        cell.swTag = indexPath.row;
    }else{
        cell.isShowSw = NO;
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return  nil;
}
-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(void)sendImgToOcr:(NSString *)base64{
    NSString * url = [DLUserDefaultModel userDefaultsModel].ocrApi;
    NSDictionary * dic = @{@"image":base64};
    [QMUITips showLoadingInView:self.view];
    [PGNetworkHelper POST:url parameters:dic cache:NO responseCache:nil success:^(id responseObject) {
        [QMUITips hideAllTips];
        NSInteger count = [responseObject[@"words_result_num"] integerValue];
        if (count>0) {
            NSArray * list = responseObject[@"words_result"];
            NSString * finalStr = @"";
            for (int i =0; i<list.count; i++) {
                NSDictionary * dic = list[i];
                if (i == 0) {
                    finalStr = dic[@"words"];
                }else{
                    finalStr = [NSString stringWithFormat:@"%@\n%@",finalStr , dic[@"words"]];
                }
            }
            [self showOCRResult:finalStr];
        }else{
            [QMUITips showError:@"无法识别内容"];
        }
    } failure:^(NSError *error) {
        [QMUITips hideAllTips];
    }];
}
-(void)showOCRResult:(NSString*)re{
    [self.view addSubview:self.shelterView];
    QRCodeInputTV * vc = [[QRCodeInputTV alloc]initWithFrame:Frame(15, IPHONE_HEIGHT/2.f-125, IPHONE_WIDTH-30, 250)];
    vc.inputContent = re;
    vc.certainBtnName = @"复制";
    vc.certainAlertMsg = @"内容已复制到剪贴板啦~";
    vc.certainClickIsCopy = YES;
    [self.shelterView addSubview:vc];
    __weak typeof(vc)weakV = vc;
    vc.aniBlock = ^(NSString * _Nonnull str) {
        [weakV removeFromSuperview];
        [self.shelterView removeFromSuperview];
        self.shelterView = nil;
    };
    vc.transform = CGAffineTransformMakeScale(0.01, 0.01);
    [UIView animateWithDuration:0.35 animations:^{
        self.shelterView.alpha = 1;
        vc.transform = CGAffineTransformMakeScale(1.0, 1.0);
    }];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        if (indexPath.row == 0) {
//            GoodsNameMgrVC * vc = [GoodsNameMgrVC new];
//            [self.navigationController pushViewController:vc animated:YES];
            [self.navigationController pushViewController:[ImageSettingVC new] animated:YES];
        }
    }else{
        if(indexPath.row==0){
            [ReuseFile getOcrMainUrl:^(id  _Nonnull response) {
                TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
                imagePickerVc.naviBgColor = ThemeColor;
                imagePickerVc.allowPickingVideo = NO;
                imagePickerVc.scaleAspectFillCrop = YES;
                imagePickerVc.showSelectBtn = NO;
                [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                    UIImage * img = photos[0];
                    NSData * jepg = [img compressImgToData:500*1024];
                    NSString * base64Str = [jepg base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
                    [self sendImgToOcr:base64Str];
                }];
                [self presentViewController:imagePickerVc animated:YES completion:nil];
            }];
        }else if (indexPath.row==1){
            [MXActionSheet showWithTitle:@"生成二维码" cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"从剪贴板粘贴", @"手动输入"] selectedBlock:^(NSInteger index) {
                if (index==1) {
                    UIPasteboard * board = [UIPasteboard generalPasteboard];
                    [self generateQrCode:board.string];
                }else if(index == 2){
                    [self.view addSubview:self.shelterView];
                    QRCodeInputTV * vc = [[QRCodeInputTV alloc]initWithFrame:Frame(15, IPHONE_HEIGHT/2.f-125, IPHONE_WIDTH-30, 250)];
                    [self.shelterView addSubview:vc];
                    __weak typeof(vc)weakV = vc;
                    vc.aniBlock = ^(NSString * _Nonnull str) {
                        if (str.length) {
                            [self generateQrCode:str];
                        }
                        [weakV removeFromSuperview];
                        [self.shelterView removeFromSuperview];
                        self.shelterView = nil;
                    };
                    vc.transform = CGAffineTransformMakeScale(0.01, 0.01);
                    [UIView animateWithDuration:0.35 animations:^{
                        self.shelterView.alpha = 1;
                        vc.transform = CGAffineTransformMakeScale(1.0, 1.0);
                    }];
                }
            }];
        }else if(indexPath.row == 2){
            ExpressCheckView * v = [[ExpressCheckView alloc]initWithFrame:Frame(15, 100, IPHONE_WIDTH-30, 50)];
            [self.view addSubview:v];
            QMUIModalPresentationViewController *modalViewController = [[QMUIModalPresentationViewController alloc] init];
            modalViewController.contentView = v;
            [modalViewController showWithAnimated:YES completion:nil];
        }else if (indexPath.row == 3){
            MoneyChangeVC * vc = [MoneyChangeVC new];
            [self.navigationController pushViewController:vc animated:YES];
        }else if (indexPath.row == 4){
            TCRedBookDealVC * vc = [TCRedBookDealVC new];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}
-(void)generateQrCode:(NSString*)str{
    UIImage * qrImg = nil;
    PINCache * ca = [[PINCache alloc]initWithName:QrCodeLogoFilePath];
    if ([ca containsObjectForKey:QrCodeLogoFilePath]) {
        UIImage * img = (UIImage*)[ca objectForKey:QrCodeLogoFilePath];
        qrImg = [SGQRCodeObtain generateQRCodeWithData:str size:500 logoImage:img ratio:0.2];
    }else{
        qrImg = [SGQRCodeObtain generateQRCodeWithData:str size:500];
    }
    XLPhotoBrowser *browser = [XLPhotoBrowser showPhotoBrowserWithImages:@[qrImg] currentImageIndex:0];
    browser.browserStyle = XLPhotoBrowserStyleSimple; // 微博样式
}
- (UIView *)shelterView{
    if (_shelterView == nil) {
        _shelterView = [[UIView alloc]initWithFrame:Frame(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)];
        _shelterView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
        _shelterView.alpha = 0;
    }
    return _shelterView;
}
@end
